package net.entelijan.cobean.bind.impl;

import java.util.Collection;

import net.entelijan.cobean.bind.IBeanProperty;
import net.entelijan.cobean.bind.IBinding;
import net.entelijan.cobean.bind.IModelChangeListener;
import net.entelijan.cobean.bind.IRemovableFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class CobeanCollectionBinding implements IBinding<IBeanProperty> {

    private static Log log = LogFactory.getLog(CobeanCollectionBinding.class);

    private static final long serialVersionUID = 1L;

    private IBeanProperty modelBeanProperty;

    public CobeanCollectionBinding(IBeanProperty modelBeanProperty) {
        super();
        this.modelBeanProperty = modelBeanProperty;
    }

    // TODO Check what do do with the removable factory.
    @Override
    public IModelChangeListener createModelChangeListener(final IBeanProperty beanProperty,
            final IBeanProperty comp, final IRemovableFactory removableFactory) {
        return new IModelChangeListener() {

            @Override
            public void updateComponent() {
                Collection<?> value = (Collection<?>) modelBeanProperty.getValue();
                log.info("[updateComponent] List was changed to" + value);
                if (comp != null) {
                    comp.setValue(value);
                }
            }

            @Override
            public void prepareComponent(Object oldVal, Object newVal) {
                // Nothing to prepare
            }

            @Override
            public String getPropertyName() {
                throw new UnsupportedOperationException("Should never be called");
            }
        };
    }

    @Override
    public String getModelProperty() {
        return this.modelBeanProperty.getPropertyName();
    }

    @Override
    public <T> T bind(T model, IBeanProperty comp) {
        throw new UnsupportedOperationException("Should never be called");
    }

}
